package com.tech.view.panel;

import com.tech.repository.dto.GoodsInfo;
import com.tech.repository.entity.Goods;
import com.tech.repository.entity.Order;
import com.tech.repository.session.UserSession;
import com.tech.service.GoodsImageService;
import com.tech.service.GoodsService;
import com.tech.service.OrderService;
import com.tech.service.impl.ServiceImplFactory;
import com.tech.util.LogProcessUtil;
import com.tech.view.common.ColorUtil;
import com.tech.view.common.FontUtil;
import com.tech.view.common.ResourcesUtil;
import com.tech.view.component.button.RoundButton;
import com.tech.view.component.button.SimpleIconButton;
import com.tech.view.component.label.LineThroughLabel;
import com.tech.view.component.label.StrokeLabel;
import com.tech.view.component.layout.ImageDisplayLayout;
import com.tech.view.dialog.GoodsPurchaseDialog;
import com.tech.view.frame.MainFrame;
import org.jdesktop.swingx.JXLabel;
import org.jdesktop.swingx.VerticalLayout;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.logging.Logger;

/**
 * 商品详情页
 */
public class GoodsDetailPanel extends JPanel implements PanelLifeCycle {
	private final static Logger LOG = LogProcessUtil.getLogger(GoodsDetailPanel.class.getName());
	private MainFrame frame;

	private GoodsInfo goodsInfo;
	private GoodsService goodsService;
	private GoodsImageService goodsImageService;
	private OrderService orderService;

	private JPanel contentPanel;
	private JPanel digitalPanel;
	private JPanel bottomPanel;

	private JLabel goodsTitle;
	private JLabel seller;
	private JLabel price;
	private JLabel secondPrice;
	private StrokeLabel condition;
	private JLabel popularity;
	private JXLabel introduce;
	private List<JLabel> imagePanels;

	private SimpleIconButton editButton;
	private SimpleIconButton delButton;
	private RoundButton purchaseButton;

	public GoodsDetailPanel(GoodsInfo goodsInfo, MainFrame frame) {
		this.goodsInfo = goodsInfo;
		this.frame = frame;
	}

	private void initService() {
		goodsService = ServiceImplFactory.getGoodsService();
		goodsImageService = ServiceImplFactory.getGoodsImageService();
		orderService = ServiceImplFactory.getOrderService();
	}

	private void initComponents() {
		contentPanel = new JPanel(new VerticalLayout());
		digitalPanel = new JPanel(new BorderLayout());
		bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		bottomPanel.setBackground(ColorUtil.LIGHT_BACKGROUND_COLOR);

		Goods goods = goodsInfo.getGoods();

		goodsTitle = new JLabel(goods.getGname());
		goodsTitle.setFont(FontUtil.TITLE_FONT.deriveFont(36f));
		goodsTitle.setForeground(ColorUtil.TITLE_FONT_COLOR);

		seller = new JLabel(goods.getUname());
		seller.setFont(FontUtil.TITLE_FONT.deriveFont(20f));
		seller.setForeground(ColorUtil.TITLE_FONT_COLOR);

		secondPrice = new JLabel(String.format("￥%.2f", goods.getGsecprice()));
		secondPrice.setFont(FontUtil.TITLE_FONT.deriveFont(36f));
		secondPrice.setForeground(ColorUtil.LIGHT_RED_COLOR);

		price = new LineThroughLabel(String.format("￥%.2f", goods.getGprice()));
		price.setForeground(ColorUtil.SHALLOW_FONT_COLOR);

		condition = new StrokeLabel(goods.getGcondition().toString(),
				FontUtil.TITLE_FONT.deriveFont(36f),
				ColorUtil.FONT_COLOR,
				1,
				ColorUtil.GOLDEN_COLOR);

		popularity = new JLabel(goods.getGpopularity() + "人浏览");

		introduce = new JXLabel(goods.getGintroduce());
		introduce.setLineWrap(true);
		introduce.setFont(FontUtil.DEFAULT_FONT);

		// 获取商品图片，注意这里没有对图片进行缩放，因此存储的时候应该是缩放后的图片
		imagePanels = goodsImageService.getImage(goodsInfo.getImages(), Integer.MAX_VALUE, -1, ResourcesUtil.CacheDir.GOODS_DETAIL.getDir())
				.stream()
				.sorted((o1, o2) -> { //将图片按照宽度由大到小排序，为了展示的时候更美观
					if (o1.getImage() == null) return 1;
					if (o2.getImage() == null) return -1;
					return o2.getImage().getWidth() - o1.getImage().getWidth();
				})
				.map(goodsImage -> new JLabel(new ImageIcon(goodsImage.getImage()))).toList();

		editButton = new SimpleIconButton(ResourcesUtil.getImage(ResourcesUtil.Image.EDIT_GOODS));
		editButton.setPreferredSize(new Dimension(40, 40));
		delButton = new SimpleIconButton(ResourcesUtil.getImage(ResourcesUtil.Image.DEL_GOODS));

		purchaseButton = new RoundButton("我想要", null, ColorUtil.GOLDEN_COLOR, 20);
		purchaseButton.setForeground(ColorUtil.MENU_BAR_COLOR);
		purchaseButton.setFont(FontUtil.TITLE_FONT.deriveFont(20f));
		purchaseButton.setPreferredSize(new Dimension(106, 42));

		delButton.setPreferredSize(new Dimension(40, 40));
	}

	private void initView() {
		JPanel leftPanel = new JPanel(new VerticalLayout());
		leftPanel.add(secondPrice);
		leftPanel.add(price);
		JPanel rightPanel = new JPanel(new VerticalLayout());
		rightPanel.add(condition);
		rightPanel.add(popularity);
		digitalPanel.add(leftPanel, BorderLayout.WEST);
		digitalPanel.add(rightPanel, BorderLayout.EAST);

		contentPanel.add(goodsTitle);
		contentPanel.add(seller);
		contentPanel.add(digitalPanel);
		contentPanel.add(Box.createVerticalStrut(50));
		contentPanel.add(introduce);
		// 这个虽然能解决问题，但刚点进去还是会闪一下
		// JPanel imagePanel = new JPanel(new WrapLayout(FlowLayout.LEFT));
		JPanel imagePanel = new JPanel(new ImageDisplayLayout());
		for (JLabel image : imagePanels) {
			imagePanel.add(image);
		}
		contentPanel.add(imagePanel);

		System.out.println(goodsInfo.getGoods());
		if (goodsInfo.getGoods().getUid() == UserSession.user.getUid()) { //卖家本人
			bottomPanel.add(editButton);
			bottomPanel.add(delButton);
		} else { //普通游客
			bottomPanel.add(purchaseButton);
		}

		setLayout(new BorderLayout());
		JScrollPane scrollPane = new JScrollPane(contentPanel);
		scrollPane.setBorder(BorderFactory.createEmptyBorder());
		add(scrollPane);
		add(bottomPanel, BorderLayout.SOUTH);
	}

	private void setListeners() {
		purchaseButton.addActionListener(e -> {
			Goods goods = goodsInfo.getGoods();
			// 先查询是否已有订单，再决定是否生成订单信息
			Order order = orderService.getOrder(UserSession.user.getUid(), goods.getGid());
			if (order == null) { // 创建订单
				order = new Order(UserSession.user.getUid(), goods.getGid(), -1, goods.getGprice(), Goods.SendMode.DELIVERY);
				order.setBoid(orderService.createOrder(order));
			}

			// 弹出购买对话框
			GoodsPurchaseDialog purchaseDialog = new GoodsPurchaseDialog(frame, order, goodsInfo, 580, 400);

		});

		delButton.addActionListener(e -> {
			int choice = JOptionPane.showConfirmDialog(frame, "确认删除该商品吗？", "提示", JOptionPane.YES_NO_OPTION);
			if (choice == JOptionPane.OK_OPTION) {
				Goods goods = goodsInfo.getGoods();
				if (goodsService.delGoods(goods.getGid())) {
					JOptionPane.showConfirmDialog(frame, "商品删除成功", "提示", JOptionPane.YES_NO_OPTION);
					frame.switchContentPanel(new IndexPanel(frame));
				} else {
					LOG.warning(goods.getGid() + " 商品删除失败\n" + goods);
				}
			}
		});

		editButton.addActionListener(e -> {
			frame.switchContentPanel(new GoodsSendPanel(frame, goodsInfo));
		});
	}

	@Override
	public void start() {
		initService();
		initComponents();
		setListeners();
		initView();
	}

	@Override
	public boolean end() {
		return true;
	}
}
